package com.ztesoft.zcm.cmdb.util;

import com.alibaba.fastjson.JSONObject;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.core.util.JsonUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Created by xu on 2019/3/6.
 */
public class RestfulUtil {
    private static final ZSmartLogger logger = ZSmartLogger.getLogger(RestfulUtil.class);

    /**
     * 调用接口查询数据(post方式)
     *
     * @param data       参数
     * @param serviceUrl restful 接口地址
     * @return JSONObject
     */
    public static JSONObject  callRestFulByObject(Object data, String serviceUrl) throws BaseAppException {
        ResponseEntity<JSONObject> resultNotify;
        logger.info("请求接口serviceUrl:{0}", serviceUrl);
        logger.info("请求参数data:{0}", JsonUtil.object2Json(data));
        RestTemplate restTemplate = new RestTemplate();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
            HttpEntity formEntity = new HttpEntity<>(data, headers);
            resultNotify = restTemplate.postForEntity(serviceUrl, formEntity, JSONObject.class);
        }
        catch (Exception e) {
            JSONObject errorObject = new JSONObject();
            errorObject.put("errorMsg", "call restful service[" + serviceUrl + "] occur exception:" + e.getMessage());
            return errorObject;
        }

        //http请求服务器响应码 200-正常（OK）
        if (resultNotify.getStatusCode() != HttpStatus.OK) {
            JSONObject errorObject = new JSONObject();
            errorObject.put("errorMsg", "call restful service[" + serviceUrl + "] response error:" + resultNotify.getBody());
            return errorObject;
        }

        JSONObject resultNotifyJson = resultNotify.getBody();
        logger.info("返回值resultNotifyJson:" + resultNotifyJson);
        return resultNotifyJson;
    }
}
